package com.example.authserver.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @author : hongsw
 * @date : 2021-11-10-22:29
 */
@EnableAuthorizationServer
@Configuration
public class AuthorizeConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private DataSource dataSource;

    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 集成到认证授权中心的第三方应用配置
     * secret要加密！！！内存和数据库中的都要！！！
     *
     * @param clients {@link org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer} client配置信息
     * @author hongsw
     * @date 2021/11/12 00:10
     **/
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 内存管理
        clients.inMemory()
                .withClient("web")
                .secret(passwordEncoder.encode("web-secret"))
                .scopes("read")
                .authorizedGrantTypes("authorization_code")
                .accessTokenValiditySeconds(7200)
                .redirectUris("https://www.baidu.com");
        // 数据库管理
        clients.withClientDetails(detailsService());
    }

    @Bean
    public ClientDetailsService detailsService() {
        return new JdbcClientDetailsService(dataSource);
    }


    /**
     * 配置授权服务器端点的属性和增强功能
     * 将之前的认证管理器暴露给端点，密码模式必须配置
     *
     * @param endpoints {@link org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer}
     * @author hongsw
     * @date 2021/11/12 00:13
     **/
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager);
    }
}